import React from 'react'
import { Router, Redirect, Navigation } from 'react-router'
import style from './style'
import { Modal, Link, TitleBar, Table, SubNav, Input, Button, Select, success as successToast, error as errorToast,PostFrame, InputList, IconFont, Tooltip } from '../../ui-components'
import { bindActionCreators } from 'redux'
import * as reviewAction from '../../actions/review.action'
import { clearAtList, fetchAtList } from '../../actions/home.action'
import { connect } from 'react-redux'
import { reduxForm } from 'redux-form'
import cx from 'classnames'
import moment from 'moment'
import { MulSelect } from '../../ui-components'
import util from '../../util'
import { u } from '../../actions/util'

moment.locale('zh-cn')
var ReactTooltip = require("react-tooltip")

function addLineBreak(item, i) {
  return (
    <span key={i}>
      {item}
      <br/>
    </span>
  )
}

//@todo 组件拆分

@connect(({ review }) => ({ review }), dispatch => ({actions: bindActionCreators({...reviewAction}, dispatch)}))
class StatusBlock extends React.Component {
  render(){
    const statusText = {
      2 : `进度：同事反馈进行中${this.props.viewMode != 'activities' ? '' : '，全部完成后就能看到所有同事反馈和主管对你的评分了'}。`,
      3 : '进度：反馈已完成。',
      4 : '该反馈活动已取消。'
    }
    return (
      <div>
        <div className={style.note}>
        {statusText[this.props.reviewTemplate.state]}
        </div>
      </div>
    )
  }
}


/**
 * 邀请组件
 * @param  {[type]} ({ review,       app } [description]
 * @return {[type]}     [description]
 */
@connect(({ review, app }) => ({ review, app }), dispatch => ({actions: bindActionCreators({fetchAtList, clearAtList, ...reviewAction}, dispatch)}))
class ReviewerBlock extends React.Component {
  state = {
    reviewers: [],
    reviewersMirror: [],
    DisReviewersMirror: [],
    isInvitationEditing: false,
    // 取消邀请
    cancelInvitation: false,
    readyInvititedUser: {}
  }
  componentDidMount() {
    this.props.actions.fetchReviewItemInvitations(this.props.itemId, this.props.viewMode)
  }
  componentWillReceiveProps(nextProps) {
    const { reviewItemInvitations={} } = this.props.review
    if (!util.isShallowEqual(reviewItemInvitations.invitedUsers, nextProps.review.reviewItemInvitations.invitedUsers) ) {
      const reviewers = nextProps.review.reviewItemInvitations.invitedUsers.map((v)=> Object.assign(v.invitedUserProfile, {status: v.status}) );
      this.setState({ 
        reviewers: reviewers,
      })
      this.setReviewerMirror();
    }
  }
  setReviewerMirror() {
    this.setState({
      reviewersMirror: [],
    });
  }
  doUpdate(newReviewers) {
    const payload = { invitedUserIds: newReviewers.map(v => {
      return {idValue: v.userId}
    }) }
    if ( !this.props.getIsSubmittable()) {//已提交之后才能请求更新接口
      this.props.actions.updateReviewItemInvitations(this.props.itemId, payload, ()=>{
        this.props.actions.fetchReviewItemInvitations(this.props.itemId, this.props.viewMode)
      })
    } else {
      this.props.onUpdateReviewers(payload)
    }
    this.setReviewerMirror();
  }
  handleRemove(v){
    this.setState({
      cancelInvitation: true,
      readyInvititedUser: v
    })
  }

  cancelInvitation() {
    const newReviewers = this.state.reviewers.filter( (item) => item.userId != this.state.readyInvititedUser.userId)
    this.setState({
      reviewers : newReviewers
    })
    this.doUpdate(newReviewers)
    this.setState({
      cancelInvitation: false,
      readyInvititedUser: {}
    })
  }

  showInvitationInput(){
    if (this.state.isInvitationEditing) {
      //this.refs.input_invite.focus()
    } else {
      this.setState({
        isInvitationEditing : true
      })
    }
  }
  handlePeopleSelect(){
    const {
      reviewersMirror = [],
    } = this.state;
    const arr = [...this.state.reviewers, ...reviewersMirror];
    this.setState({
      reviewers: arr,
      isInvitationEditing : false,
    })
    this.doUpdate(arr)
  }
  handleSelect(obj) {
    const item = obj.pop();
    this.setState({
      reviewersMirror: item ? [item] : [],
    });
  }
  render(){
    const { reviewItemInvitations={} } = this.props.review
    const managerUser = reviewItemInvitations.managerUser ? reviewItemInvitations.managerUser.invitedUserProfile : {}
    const invitedUsers = this.state.reviewers
    const {
      reviewersMirror = [],
    } = this.state;
    const { atList } = this.props.app
    let value = [], disValue = [];
    return (
      <div className={style.bright_form} style={{marginTop: '20px'}}>
        <h3>受邀反馈者</h3>
        {/*
        <div className={style.invite}>
                  <InputList
                    label="邀请反馈同事"
                    ref="input_invite"
                    fetch={value => this.props.actions.fetchAtList({
                      keyword: value,
                      type: 2
                    })}
                    autoFocus={true}
                    clear={this.props.actions.clearAtList}
                    onSelect={::this.handlePeopleSelect}
                    keep={false}
                    excludeList={[this.props.app.profile, ...invitedUsers, managerUser]}
                    list={atList}
                  />
                </div> 
        */}
        <ul className={style.reviewer_list}>
          {
            managerUser ? (
              <li>
                <div
                  className={cx({
                    [style.avatar]: true,
                    [style.large]: true,
                    [style.avatar_na]: ! managerUser.avatarUrl
                  })}
                  style={{backgroundImage:`url(${managerUser.avatarUrl})`}}>
                </div>
                {managerUser.fullName}
              </li> ) : null
          }
          {
            invitedUsers.map((v, i) => {
              return (
                <li key={i}>
                  { this.props.isInvitationEditable && ( !v.status || v.status === 3 ) ? <div className={style.remove} onClick={() => this.handleRemove(v)}>×</div> : null }
                  <div
                    className={cx({
                      [style.avatar]: true,
                      [style.large]: true,
                      [style.avatar_na]: !v.avatarUrl
                    })}
                    style={{backgroundImage:`url(${v.avatarUrl})`}}>
                  </div>
                  {v.fullName}
                </li>
              )
            })
          }
          {
            this.props.isInvitationEditable ? (
              <li style={{background:'#fff'}}>
                <div 
                  className={style.btn_add}
                  onClick={::this.showInvitationInput}
                  data-tip="邀请更多同事向你反馈"
                />
              </li>
            ) : null
          }
        </ul>
        {
          this.state.isInvitationEditing
            ? (
                <div style={{display:'flex','alignItems':'flex-start'}}>
                  <div style={{width: '300px',marginBottom:'-10px'}}>
                    <MulSelect 
                      placeholder="邀请反馈同事"
                      value={[...reviewersMirror]}
                      fetch={value => {
                        if (value)
                          this.props.actions.fetchAtList({
                            keyword: value,
                            type: 2
                          });
                        else
                          this.props.actions.clearAtList();
                      }}
                      getItemAttrs={(item) => {
                        return {
                          label: item.fullName,
                          img: item.avatarUrl,
                        }
                      }}
                      onSelect={::this.handleSelect}
                      options={atList}
                      excludeList={[this.props.app.profile, ...invitedUsers, managerUser ]}
                      disabled={!this.props.isInvitationEditable}
                    />  
                  </div>
                  &nbsp;
                  <Button className={style.button_save} label="提交" onClick={::this.handlePeopleSelect}/> 
                </div>
              )
            : null 
        }
        <Modal
          onRequestClose={() => this.setState({ cancelInvitation: false })}
          active={this.state.cancelInvitation}
          actions={[
            'cancel',
            ::this.cancelInvitation
          ]}
          title="取消邀请"
        >
          <div>确定取消邀请{ this.state.readyInvititedUser.fullName || ''  }？</div>
        </Modal>
        
      </div>
    )
  }
}


/**
 * 项目反馈模板
 * @param  {[type]} ({ review,       app } [description]
 * @return {[type]}     [description]
 */
@connect(({ review, app }) => ({ review, profile: app.profile }), dispatch => ({actions: bindActionCreators({...reviewAction}, dispatch)}))
class ProjectBlock extends React.Component {
  state = {
    isUnfolded: true,
    isRevieweeEdit: this.props.project.comment === null,
    isReviewerEdit: this.props.project.reviewerComment === null,
    isCommentEditInit: true,
    reviewerCommentId: null,
    isDeleted: false,
    deleteReviewProject: false,
    deleteReviewProjectComment: false
  }
  componentDidMount() {
    this.props.actions.fetchReviewProject(
      this.props.itemId, 
      this.props.project.projectId || this.props.project.idValue, 
      this.props.index, 
      this.props.viewMode
    )
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      reviewerCommentId: (nextProps.project.reviewerComment && nextProps.project.reviewerComment.commentId ) || nextProps.review.newProjectCommentId
    })
    if (! nextProps.project.reviewerComment) {
      this.setState({ isReviewerEdit: true })
    }
    if (nextProps.project.reviewerComment && nextProps.project.reviewerComment.content) {
      this.setState({ isCommentEditInit: false })
    }
  }
  // handleToggle() {
  //   return;
  //   if (this.state.isUnfolded) {
  //     this.setState({isUnfolded: false})
  //   } else {
  //     this.props.actions.fetchReviewProject(
  //       this.props.itemId,
  //       this.props.project.projectId,
  //       this.props.index,
  //       this.props.viewMode
  //     )
  //     this.setState({isUnfolded: true})
  //   }
  // }
  handleUpdateProject() {
    this.refs.projectEditForm.submit()
  }
  updateProject(data) {
    if (
      data.name &&
      data.role &&
      data.score &&
      data.comment
    ) {
      this.props.actions.updateReviewProject(this.props.itemId, 
        this.props.project.projectId, 
        data, 
        ()=> {
          this.props.actions.fetchReviewProject(
            this.props.itemId,
            this.props.project.projectId,
            this.props.index,
            this.props.viewMode
          )
          this.setState({isRevieweeEdit: false})
          this.props.actions.decreaseUnready()
        }
      )
    }else{
      errorToast('请填写完整')
    }
  }
  handleReviewerSubmit() {
    const callback = () => {
      this.props.project.reviewerComment = {content: this.refs.reviewerCommentContent.value}
      this.setState({isReviewerEdit: false})
    }
    if (this.refs.reviewerCommentContent.value) {
      if (this.state.reviewerCommentId) {
        this.props.actions.updateReviewerProjectComment(
          this.props.itemId, 
          this.props.project.projectId, 
          this.state.reviewerCommentId,
          {content: this.refs.reviewerCommentContent.value},
          callback
        )
      } else {
        this.props.actions.addReviewerProjectComment(
          this.props.itemId, 
          this.props.project.projectId, 
          {content: this.refs.reviewerCommentContent.value},
          callback
        )
      }
      
    } else {
      errorToast('请填写完整')
    }
  }

  handleRemove() {
    this.setState({
      deleteReviewProject: true
    })
  }

  deleteReviewProject() {
    this.props.actions.deleteReviewProject(
      this.props.itemId,
      this.props.project.projectId,
      ()=> {
        successToast('删除成功!')
        this.setState({isDeleted: true})
      }
    )
    this.setState({deleteReviewProject: false})
  }

  deleteReviewProjectComment() {
    this.props.actions.deleteReviewProjectComment(
      this.props.itemId,
      this.props.project.projectId,
      this.state.readyDeletedReviewProjectCommentId,
      ()=> {
        this.props.project.reviewerComment = {}
        this.setState({isReviewerEdit: true, isCommentEditInit: true})
        successToast('删除成功!')
      }
    )
    this.setState({
      deleteReviewProjectComment: false,
      readyDeletedReviewProjectCommentId: null
    })
  }

  handleDeleteComment(commentId) {
    this.setState({
      deleteReviewProjectComment: true,
      readyDeletedReviewProjectCommentId: commentId
    })
  }

  render() {
    const { reviewerComment={} } = this.props.project
    const reviewerCommentContent = reviewerComment ? reviewerComment.content : ''
    const reviewerCommentId = this.state.reviewerCommentId
    return (
      <div style={{
        display: this.state.isDeleted ? 'none' : 'block',
        position: 'relative',
        width: '600px',
        marginBottom: '10px',
        background: this.state.isUnfolded ? '#f3f6f9' : '#fff',
        padding: this.state.isUnfolded ? '20px' : '10px'
      }}>
        {
          this.props.isProjectDeleteable && ! this.state.isRevieweeEdit
              ? <Link className={style.remove} color="red" onClick={::this.handleRemove}>删除项目</Link> 
              : null 
        }
        <h3 
          style={{fontWeight: 'normal', fontSize: '20px', color: '#333'}} 
        >
          项目：{this.props.project.name}
        </h3>
        {
          this.state.isUnfolded ? (
            <div>
            {
              this.state.isRevieweeEdit ? (
                  <div className={style.dark_form} style={{margin: '5px 0 0 -20px'}}>
                    <ProjectForm formKey={this.props.index.toString()} initialValues={this.props.project} project={this.props.project} ref="projectEditForm" onSubmit={::this.updateProject} />
                    <div className={style.operate} style={{padding:'10px 0 0 100px'}}>
                      <Button className={style.button_save} label="保存" onClick={::this.handleUpdateProject} /> 
                      <Link className={style.button_cancel} onClick={() => {
                        this.setState({isRevieweeEdit: false})
                        this.props.actions.decreaseUnready()
                      }} label="取消"/>
                    </div>
                  </div>
                ) : (
                  <div>
                    <div style={{padding: '5px 0'}}>角色：{this.props.project.role} 贡献度：{this.props.project.score}</div>
                    <div className={style.divider}><span>&lt; 自评 &gt;</span></div>
                    <div className={style.content}>
                    {
                      (this.props.project.comment || '').split("\n").map(addLineBreak)
                    }
                    </div>
                    {
                      this.props.isProjectEditable ? (<div className={style.operate}>
                        <Button label="修改" style={{background:'#58c6b5', color:'#fff'}} onClick={ () => {
                          this.setState({isRevieweeEdit: true})
                          this.props.actions.increaseUnready()
                        }} /> 
                      </div>) : null
                    }
                    
                  </div>
                )
            }
            {
              this.props.viewMode != 'activities' && <div className={style.divider}><span>&lt; 反馈 &gt;</span></div>
            }
            {
              this.props.isShowPeerComments && this.props.project.submittedComments ? this.props.project.submittedComments.map((v, i)=>{
                return v.userProfile.userId != this.props.profile.userId ? (
                  <div key={i}>
                    <div className={style.member}>
                      <div
                        className={cx({
                          [style.avatar]: true,
                          [style.avatar_na]: ! v.userProfile.avatarUrl
                        })}
                        style={{backgroundImage:`url(${v.userProfile.avatarUrl})`}}></div>
                      {v.userProfile.fullName}
                    </div>
                    <div className={style.content}>
                      {(v.content || '').split("\n").map(addLineBreak)}
                    </div>
                  </div>
                ) : null

              }) : null
            }
            {
              this.props.viewMode == 'invitations' ? (
                this.state.isReviewerEdit ? (
                  this.state.isCommentEditInit ? (
                    <div
                      className={style.input_init}
                      onClick={() => {
                        this.setState({isCommentEditInit: false})
                        this.props.actions.increaseUnready()
                      }}
                    >
                      添加我的反馈...
                    </div>
                  ) : (
                    <div>
                      <div 
                        className={cx({
                          [style.avatar]: true,
                          [style.avatar_na]: ! this.props.profile.avatarUrl
                        })} 
                        style={{backgroundImage:`url(${this.props.profile.avatarUrl})`}}></div>
                      <textarea autoFocus ref="reviewerCommentContent" id="" cols="60" rows="5" defaultValue={reviewerCommentContent}/>
                      <div className={style.operate} style={{padding:'0 0 0 37px'}}>
                        <Button className={style.button_save} label="保存" onClick={::this.handleReviewerSubmit} />
                        <Link className={style.button_cancel}  onClick={() => {
                            this.setState({isCommentEditInit: true})
                            this.props.actions.decreaseUnready()
                          }} label="取消"/>
                      </div>
                    </div>
                  )
                ) : (
                  <div style={{position: 'relative'}}>
                    {
                      this.props.isCommentEditable
                          ? <Link className={style.remove} color="red" onClick={() => this.handleDeleteComment(reviewerCommentId)}>删除反馈</Link> 
                          : null 
                    }
                    <div className={style.member}>
                      <div
                        className={cx({
                          [style.avatar]: true,
                          [style.avatar_na]: ! this.props.profile.avatarUrl
                        })}
                        style={{backgroundImage:`url(${this.props.profile.avatarUrl})`}}></div>
                      {this.props.profile.fullName}
                    </div>
                    <div className={style.content}>
                      {(reviewerCommentContent || '').split("\n").map(addLineBreak)}
                    </div>
                    {
                      this.props.isCommentEditable ? <Button label="修改" style={{background:'#58c6b5', color:'#fff'}} onClick={ () => this.setState({isReviewerEdit: true})} /> : null
                    }
                  </div>
                )
              ) : null
            }
            </div>
          ): null
        }
        <Modal
          onRequestClose={() => this.setState({ deleteReviewProjectComment: false })}
          active={this.state.deleteReviewProjectComment}
          actions={[
            'cancel',
            ::this.deleteReviewProjectComment
          ]}
          title="删除反馈项目评论"
        >
          <div>确定删除吗？</div>
        </Modal>
        <Modal
          onRequestClose={() => this.setState({ deleteReviewProject: false })}
          active={this.state.deleteReviewProject}
          actions={[
            'cancel',
            ::this.deleteReviewProject
          ]}
          title="删除反馈项目"
        >
          <div>确定删除吗？</div>
        </Modal>
      </div>
    )
  }
}

class ProjectForm extends React.Component { 
  state = {
    data: {}
  }
  componentDidMount() {
  }
  render(){
    const {fields: {projectId, name, role, score, comment}, handleSubmit} = this.props;
    return (
      <table className={style.project_form}>
        <tbody>
          <tr>
            <th>项目名称：</th>
            <td>
              <Input type="text" {...name}/>
            </td>
          </tr>
          <tr>
            <th>
              <Tooltip style={{marginRight: '5px'}} tip="指你在项目中扮演的角色，如：<br /><br />负责人<br />主要贡献者<br />提供帮助" />
              你的角色：
            </th>
            <td>
              <Input type="text" {...role}/>
            </td>
          </tr>
          <tr>
            <th>
              <Tooltip style={{marginRight: '5px'}} tip="贡献度用于标记你的工作对项目的影响程度，5为最高，1为最低。" />
              贡献度：
            </th>
            <td className="select">
              <Select 
                {...score}
                value={score.value || ''}
                style={{display:'inline-block'}}
              >
                <option value='0'>请选择</option>
                <option value='1'>1</option>
                <option value='2'>2</option>
                <option value='3'>3</option>
                <option value='4'>4</option>
                <option value='5'>5</option>
              </Select>
            </td>
          </tr>
          <tr>
            <th>描述及自评 ：</th>
            <td>
              <Input
                multi
                {...comment}
                value={comment.value || ''}/>
            </td>
          </tr>
        </tbody>
      </table>
    )
  }
}
ProjectForm = reduxForm({
    form: 'ProjectForm', // a unique name for this form
    fields: ['projectId', 'name', 'role', 'score', 'comment']
  }
)(ProjectForm)



@connect(({ app }) => ({ profile: app.profile }), dispatch => ({actions: bindActionCreators({...reviewAction}, dispatch)}))
class QuestionBlock extends React.Component {
  state = {
    isReady: true,
    isRevieweeEdit: ! this.props.question.revieweeComment && this.props.viewMode == 'activities',
    RevieweeCommentId: this.props.question.revieweeComment && this.props.question.revieweeComment.commentId,
    isReviewerEdit: ! this.props.question.reviewerComment,
    ReviewerCommentId: this.props.question.reviewerComment && this.props.question.reviewerComment.commentId,
    isCommentEditInit: this.props.viewMode == 'invitations' 
        ? ( ! this.props.question.reviewerComment )
        : ( ! this.props.question.revieweeComment )
  }
  componentDidMount() {
    this.setState({RevieweeCommentId: this.props.question.revieweeComment && this.props.question.revieweeComment.commentId})
    this.setState({ReviewerCommentId: this.props.question.reviewerComment && this.props.question.reviewerComment.commentId})
    if ((this.props.viewMode == 'activities' && ! this.state.RevieweeCommentId)
      || (this.props.viewMode != 'activities' && ! this.state.ReviewerCommentId))
     {
      this.updateReadyState(false);
    }
  }
  componentWillReceiveProps(nextProps) {
    this.setState({RevieweeCommentId: nextProps.question.revieweeComment && nextProps.question.revieweeComment.commentId})
    this.setState({ReviewerCommentId: nextProps.question.reviewerComment && nextProps.question.reviewerComment.commentId})
  }
  handleRevieweeSubmit(){
    const callback = () => {
      this.props.question.revieweeComment = {content: this.refs.content.value}
      this.setState({isRevieweeEdit: false})
      this.updateReadyState(true)
    }
    if (this.refs.content.value) {
      if (this.state.RevieweeCommentId) {
        this.props.actions.updateRevieweeComment(
          this.props.itemId, 
          this.props.question.questionId, 
          this.state.RevieweeCommentId,
          {content: this.refs.content.value},
          callback
        )
      } else {
        this.props.actions.addRevieweeComment(
          this.props.itemId, 
          this.props.question.questionId, 
          {content: this.refs.content.value},
          callback
        )
      }

      
    }else{
      errorToast('请填写完整')
    }
  }
  handleReviewerSubmit(){
    const callback = () => {
      this.props.question.reviewerComment = {content: this.refs.content.value}
      this.setState({isReviewerEdit: false})
      this.props.actions.decreaseUnready()
      this.updateReadyState(true)
    }
    if (this.refs.content.value) {
      if (this.state.ReviewerCommentId) {
        this.props.actions.updateReviewerComment(
          this.props.itemId, 
          this.props.question.questionId, 
          this.state.ReviewerCommentId,
          {content: this.refs.content.value},
          callback
        )
      } else {
        this.props.actions.addReviewerComment(
          this.props.itemId, 
          this.props.question.questionId, 
          {content: this.refs.content.value},
          callback
        )
      }

      
    }else{
      errorToast('请填写完整')
    }
  }
  updateReadyState(isGotReady){
    if (isGotReady &&  ! this.state.isReady) {
      this.props.actions.decreaseUnready()
      this.setState({isReady: true})
    } else if (this.state.isReady){
      this.setState({isReady: false})
      this.props.actions.increaseUnready()
    } else {
      //已经ready再提交ready，或已经unready再提交unready，两种情况都不应存在，什么都不做
    }
  }
  render(){
    let {name, revieweeComment={}, reviewerComment={}} = this.props.question
    revieweeComment = revieweeComment ? revieweeComment : {}
    reviewerComment = reviewerComment ? reviewerComment : {}
    const revieweeUserProfile = this.props.revieweeUserProfile
    const isShowPeerComments = (this.props.viewMode != 'activities' || this.props.reviewTemplate.state == 3)

    return (
      <div className={style.question_block}>
        <h3 style={{fontWeight: 'normal', padding: '5px 0', fontSize: '20px', color: '#333'}}>{name}</h3>
        <div className={style.divider}><span>&lt; 自评 &gt;</span></div>
        {
          this.state.isRevieweeEdit ? (
            this.state.isCommentEditInit ? (
              <div
                className={style.input_init}
                onClick={() => this.setState({isCommentEditInit: false})}
              >
                添加自评...
              </div>
            ) : (
              <div>
                <div
                  className={cx({
                    [style.avatar]: true,
                    [style.avatar_na]: ! revieweeUserProfile.avatarUrl
                  })}
                  style={{backgroundImage:`url(${revieweeUserProfile.avatarUrl})`}}></div>
                <textarea autoFocus ref="content" id="" cols="60" rows="5" defaultValue={revieweeComment.content}/>
                <div className={style.operate} style={{padding:'0 0 0 37px'}}>
                  <Button className={style.button_save} label="保存" onClick={::this.handleRevieweeSubmit} />
                  <Link 
                    className={style.button_cancel} 
                    onClick={() => {
                      if(revieweeComment.content) {
                        this.setState({isRevieweeEdit: false})
                        this.updateReadyState(true)
                      } else {
                        this.setState({isCommentEditInit: true})
                      }
                    }} 
                    label="取消"
                  />
                </div>
              </div>
            )
          ) : (
            <div>
              <div className={style.member}>
                <div
                  className={cx({
                    [style.avatar]: true,
                    [style.avatar_na]: ! revieweeUserProfile.avatarUrl
                  })}
                  style={{backgroundImage:`url(${revieweeUserProfile.avatarUrl})`}}></div>
                {revieweeUserProfile.fullName}
              </div>
              <div className={style.content}>
                {(revieweeComment.content || '（自评暂未撰写）').split("\n").map(addLineBreak)}
              </div>
              {
                this.props.isAnswerEditable ? (<Button label="修改" style={{background:'#58c6b5', color:'#fff'}} onClick={ () => {
                    this.setState({isRevieweeEdit: true})
                    this.updateReadyState(false)
                  }} />) : null
              }
            </div>
          )
        }
        {
          this.props.viewMode != 'activities' && <div className={style.divider}><span>&lt; 反馈 &gt;</span></div>
        }
        {
          this.props.isShowPeerComments && this.props.question.submittedComment ? this.props.question.submittedComment.map((v, i)=>{
            return v.userProfile.userId != this.props.profile.userId ? (
              <div key={i}>
                <div className={style.member}>
                  <div
                  className={cx({
                    [style.avatar]: true,
                    [style.avatar_na]: ! v.userProfile.avatarUrl
                  })}
                  style={{backgroundImage:`url(${v.userProfile.avatarUrl})`}}></div>
                  {v.userProfile.fullName}
                </div>
                <div className={style.content}>
                  {(v.content || '').split("\n").map(addLineBreak)}
                </div>
              </div>
            ) : null

          }) : null
        }
        {
          this.props.viewMode == 'invitations' ? (
            this.state.isReviewerEdit ? (
              this.state.isCommentEditInit ? (
                <div
                  className={style.input_init}
                  onClick={() => this.setState({isCommentEditInit: false})}
                >
                  添加我的反馈...
                </div>
              ) : (
                <div>
                  <div
                    className={cx({
                      [style.avatar]: true,
                      [style.avatar_na]: ! this.props.profile.avatarUrl
                    })}
                    style={{backgroundImage:`url(${this.props.profile.avatarUrl})`}}></div>
                  <textarea autoFocus ref="content" id="" cols="60" rows="5" defaultValue={reviewerComment.content}/>
                  <div className={style.operate} style={{padding:'0 0 0 37px'}}>
                    <Button className={style.button_save} label="保存" onClick={::this.handleReviewerSubmit} />
                    <Link className={style.button_cancel} onClick={() => {
                      if(reviewerComment.content) {
                        this.setState({isReviewerEdit: false})
                        this.updateReadyState(true)
                      } else {
                        this.setState({isCommentEditInit: true})
                      }
                    }} label="取消"/>
                  </div>
                </div>
              )
            ) : (
              <div>
                <div className={style.member}>
                  <div
                    className={cx({
                      [style.avatar]: true,
                      [style.avatar_na]: ! this.props.profile.avatarUrl
                    })}
                    style={{backgroundImage:`url(${this.props.profile.avatarUrl})`}}></div>
                  {this.props.profile.fullName}
                </div>
                <div className={style.content}>
                  {(reviewerComment.content || '').split("\n").map(addLineBreak)}
                </div>
                {
                  this.props.isCommentEditable ? (<Button label="修改" style={{background:'#58c6b5', color:'#fff'}} onClick={ () => {
                    this.setState({isReviewerEdit: true})
                    this.updateReadyState(false)
                  }} />) : null
                }
              </div>
            )
          ) : null
        }
      </div>
    )
  }
}


export default
@connect(({ review, app }) => ({ review, profile: app.profile }), dispatch => ({actions: bindActionCreators({...reviewAction}, dispatch)}))
class ReviewItem extends React.Component {
  state = {
    isShowProjectForm: false,
    viewMode: 'invitations',
    itemId: '',
    invitedReviewers: [],
    score: 0,
    readyRefusedInvitationId: null,
    refuseInvitation: false,
  }
  static contextTypes = {
    router: React.PropTypes.object
  }
  componentDidMount() {
    const { itemId, viewMode } = this.props.params
    this.props.actions.fetchReviewItem(itemId, viewMode)
    //this.props.actions.fetchReviewItemInvitations(itemId, viewMode)
  }
  componentWillReceiveProps(props) {
    this.setState({
      score: props.review.reviewItem.score
    })
    const { itemId, viewMode } = props.params
    if (itemId !== this.props.params.itemId) {
      this.props.actions.clearReviewItem()
      this.props.actions.fetchReviewItem(itemId, viewMode)
      //this.props.actions.fetchReviewItemInvitations(itemId, viewMode)
    }
  }
  componentWillUnmount() {
    this.props.actions.clearReviewItem()
  }
  getIsSubmittable = () => {
    const viewMode = this.props.params.viewMode
    const {reviewItem={}} = this.props.review;
    const {invitationDisplayType = 4, activityDisplayType = 3} = reviewItem;
    if(viewMode === 'activities')
      return !!~[1,4].indexOf(activityDisplayType);
    else
      return !!~[2,3,5].indexOf(invitationDisplayType);
  }
  handleAddProject() {
    const { itemId, viewMode } = this.props.params
    this.refs.addProject.submit()
  }
  createProject(data) {
    const { itemId, viewMode } = this.props.params
    if (
      data.name &&
      data.role &&
      data.score &&
      data.comment
    ) {
      this.props.actions.createReviewProject(itemId, data, ()=>{
        this.setState({isShowProjectForm: false})
        this.props.actions.decreaseUnready()
      })
      
    }else{
      errorToast('请填写完整')
    }
  }
  handleUpdateReviewers(payload) {
    this.setState({invitedReviewers: payload.invitedUserIds})
  }
  submitSelfReview() {
    const { itemId, viewMode } = this.props.params;
    const {reviewItem={}} = this.props.review;

    const {templateId} = reviewItem.reviewTemplate;
   
    this.props.actions.submitSelfReview(itemId, viewMode, {invitedUserIds: this.state.invitedReviewers}, () => {
      this.context.router.push(`/review/index/${templateId}`);
      alert('自评提交成功！')
    })
  }
  submitPeerReview(isManager) {
    const { itemId, viewMode } = this.props.params;
    const {reviewItem={}} = this.props.review;

    const {templateId} = reviewItem.reviewTemplate;
    if ( isManager && ! this.state.score) {
      errorToast('请填写评分')
      return false
    }
    this.props.actions.submitPeerReview(itemId, 
      viewMode, 
      {invitedUserIds: [], score: this.state.score},
      ()=> {
        this.context.router.push(`/review/index/${templateId}`);
        alert('反馈提交成功！')
      }
    )
  }
  refuseInvitation() {
    const { itemId, viewMode } = this.props.params;
    const {reviewItem={}} = this.props.review;
    const {templateId} = reviewItem.reviewTemplate;
    this.setState({
      readyRefusedInvitationId: null,
      refuseInvitation: false
    })
    this.props.actions.refuseInvitation(this.state.readyRefusedInvitationId, ()=> {
      this.context.router.push(`/review/index/${templateId}`);
      success('删除邀请成功!')
    })
    
  }
  handleRefuse(invitationId) {
    this.setState({
      refuseInvitation: true,
      readyRefusedInvitationId: invitationId
    })
  }
  render() {
    const itemId = this.props.params.itemId
    const viewMode = this.props.params.viewMode
    const {reviewItem={}, unreadyNum, reviewItemProjects=[]} = this.props.review

    const {activityId, invitationId, reviewTemplate={}, isManager, isProjectAddable, orgId, pastInvitations=[], questions=[], revieweeUserProfile={}, score, templateId} = reviewItem
    const isSubmittable = this.getIsSubmittable();
    const projects = reviewItemProjects
    let isProjectEditable = false
    let isProjectDeleteable = false
    let isAnswerEditable = false//通用自评只能编辑不能增删

    let isCommentEditable = false//包含修改和删除（反馈）
    let isInvitationEditable = false//调整邀请
    let isShowPeerComments = false//展示同事反馈
    let isReadyToSubmit = false//反馈提交状态验证

    if(viewMode == 'activities'){
      if (reviewTemplate.selfReviewDeadline > Date.now()) {//自评截止日前
        isProjectEditable = true
        isProjectDeleteable = isSubmittable//未提交，可删
        isAnswerEditable = true
        isInvitationEditable = true
      }else if (reviewTemplate.peerReviewDeadline > Date.now()){//同事反馈截止日前
        isProjectEditable = isSubmittable
        isProjectDeleteable = isSubmittable
        isAnswerEditable = isSubmittable
        isInvitationEditable = isSubmittable
      }else if (reviewTemplate.publicDeadline > Date.now()){//流程结束前
      }else if (reviewTemplate.publicDeadline < Date.now()){//流程结束后
        isShowPeerComments = true
      }
    }else if(viewMode == 'invitations'){
      if (reviewTemplate.peerReviewDeadline > Date.now()){//同事反馈截止日前
        isCommentEditable = true
        isShowPeerComments = isManager
      }else if (reviewTemplate.publicDeadline > Date.now()){//流程结束前
        isCommentEditable = isSubmittable
        isShowPeerComments = isManager
      }else if (reviewTemplate.publicDeadline < Date.now()){//流程结束后
        isShowPeerComments = true
        isCommentEditable = isSubmittable
      }
    }
    
    return (
      reviewItem ? (
        <div style={{display: !!revieweeUserProfile.fullName ? 'block' : 'none'}}>
          <ReactTooltip multiline effect="solid" />
          <TitleBar label={viewMode == 'invitations' ? `给${revieweeUserProfile.fullName}的反馈` : `${revieweeUserProfile.fullName}的自评`} back={`/review/index/${reviewItem.reviewTemplate ? reviewItem.reviewTemplate.templateId : 'default'}`} />
          <div style={{marginTop:'5px', height: '30px'}}>
            <div style={{float:'left',lineHeight:'30px',paddingRight:'20px',color:'#999'}}>
              活动名称：<span 
                  style={{color:'#999',
                    paddingRight:'10px',
                    display: 'inline-block',
                    maxWidth: '240px',
                    overflow: 'hidden',
                    height: '30px',
                    whiteSpace: 'nowrap',
                    verticalAlign: 'top',
                    textOverflow: 'ellipsis'}}
                  title={reviewTemplate.templateName}>{reviewTemplate.templateName}</span> 
              工作阶段：<span>
              {moment(reviewTemplate.startTime).format('YYYY-MM-DD')} ~ {moment(reviewTemplate.endTime).format('YYYY-MM-DD')}</span>
            </div>
            {
              viewMode != 'activities' ? (
              <div style={{display:'inline-block',width:'200px'}}>
                <Select 
                    ref='selectOne' 
                    onChange={
                      e =>{
                        if(!e.target.value) return;
                        this.context.router.push(`/review/item/${e.target.value}/${viewMode}`);
                       }
                     }
                    style={{display:'inline-block'}}>
                  <option value=''>以往反馈活动...</option>
                  {
                    pastInvitations ? pastInvitations.map((v, i) => {
                      return  <option key={i} value={v.invitationId}>{v.templateName}</option>
                    }) : null
                  }
                </Select>
              </div> ) : null
            }
          </div>
          {
            ((viewMode == 'activities' && !isSubmittable) || isManager ) ? 
              ( 
              <StatusBlock
                viewMode={viewMode}
                reviewTemplate={reviewTemplate} 
              /> 
              ): null
          }
          <div className={style.projects}>
            {
              projects.map((v, i) => {
                return ( <ProjectBlock
                  viewMode={viewMode} 
                  reviewTemplate={reviewTemplate}
                  isProjectEditable={isProjectEditable}
                  isProjectDeleteable={isProjectDeleteable}
                  isCommentEditable={isCommentEditable}
                  isShowPeerComments={isShowPeerComments}
                  key={i}
                  project={v}
                  itemId={itemId}
                  index={i}
                /> )
              })
            }
          </div>
          <div>
            {
              isProjectAddable && ! this.state.isShowProjectForm
                ? <Button green label="添加反馈项目" data-tip="评价自己完成过的项目，并邀请同事针对项目进行反馈" style={{background:'#58c6b5', color:'#fff'}} onClick={ ()=> {
                    this.setState({isShowProjectForm: true}) 
                    this.props.actions.increaseUnready()
                  }}/> 
                : null
            }
            {
              this.state.isShowProjectForm ? (
                <div className={style.dark_form} style={{marginTop: '5px'}}>
                  <ProjectForm ref="addProject" onSubmit={::this.createProject} />
                  <div className={style.operate} style={{padding:'10px 0 0 100px'}}>
                    <Button className={style.button_save} label="添加" onClick={::this.handleAddProject} />
                    <Link style={{display:'inline-block',color: '#777'}} onClick={() => {
                        this.setState({isShowProjectForm: false})
                        this.props.actions.decreaseUnready()
                      }} label="取消"/>
                  </div>
                </div>) : null
            }
          </div>
          {
            questions.map((v, i) => {
              return (
                <QuestionBlock
                  key={i}
                  question={v}
                  itemId={itemId}
                  viewMode={viewMode}
                  reviewTemplate={reviewTemplate} 
                  isAnswerEditable={isAnswerEditable}
                  isCommentEditable={isCommentEditable}
                  isShowPeerComments={isShowPeerComments}
                  index={i}
                  revieweeUserProfile={revieweeUserProfile}
                />
              )
            })
          }
          {
            isManager || ((reviewTemplate||{}).state === 3 && (util.isEqual(revieweeUserProfile||{}).userId, u.userId ) ) ? (
              <div style={{padding: '30px 0', fontSize:'14px', lineHeight:'30px'}} >
              主管评分：
                <div style={{display:'inline-block', height:'20px', width:'80px'}}>
                  {
                    isSubmittable ? (
                  <Select 
                      ref='selectOne' 
                      value={this.state.score}
                      onChange={
                        e =>{
                          this.setState({
                            score: e.target.value
                          })
                         }
                       }
                      style={{display:'inline-block'}}>
                    <option value='0'>请选择</option>
                    <option value='1'>1</option>
                    <option value='2'>2</option>
                    <option value='3'>3</option>
                    <option value='4'>4</option>
                    <option value='5'>5</option>
                  </Select> ) : <span>{score}分</span>
                  }
                </div>
              </div>
            ) : null
          }
          {
            (viewMode == 'activities' || viewMode == 'report') ? (
              <div>
                <ReviewerBlock
                  itemId={itemId}
                  isSubmittable={isSubmittable}
                  isInvitationEditable={isInvitationEditable}
                  viewMode={viewMode}
                  onUpdateReviewers={::this.handleUpdateReviewers}
                  getIsSubmittable={this.getIsSubmittable}
                />
                {
                  isSubmittable ? <Button label="提交自评" style={{marginTop: '20px', height:'40px', width:'180px'}} onClick={::this.submitSelfReview} disabled={unreadyNum > 0} data-tip={unreadyNum > 0 ? '请完成所需填写项后提交':'点击提交，将向您选定的同事发送反馈邀请'} /> : null
                }
              </div>) : null
          }
          {
            (viewMode == 'invitations' && isSubmittable) ? (
              <div>
              <Button label={`${this.state.score ? '更新': '提交'}反馈`} style={{marginTop: '20px', height:'40px', width:'180px',display:'inline-block'}} onClick={this.submitPeerReview.bind(this,isManager)} disabled={unreadyNum > 0} data-tip={unreadyNum > 0 ? '请完成所需填写项后提交':'点击提交，流程结束后对方与对方的主管将能看到你的反馈'} />
                {
                  ! isManager ? <Link style={{ marginTop: '4px',marginLeft: '30px'}} color="red" onClick={()=> this.handleRefuse(invitationId)}>拒绝邀请</Link> : null
                }
              </div>
            ) : null
          }
          <Modal
            onRequestClose={() => this.setState({ refuseInvitation: false })}
            active={this.state.refuseInvitation}
            actions={[
              'cancel',
              ::this.refuseInvitation
            ]}
            title="拒绝邀请"
          >
            <div>确定拒绝对方的反馈邀请？</div>
          </Modal>
        </div>
      ) : null
    )
  }
}
